package com.zhiyou100.review.day021.mysocket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @packageName: TestMySocket
 * @className: com.zhiyou100.review.day021.mysocket
 * @Description: TODO socket 服务器
 * @author: yang
 * @date: 7/2/20
 */
public class TestMySocket {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(10086);
        // 创建ServerSocket服务，并开启指定端口
        Socket accept = serverSocket.accept();
        InputStream inputStream = accept.getInputStream();
        // 等待客户端的连接 Socket套接字，传输通道
        // accept是阻塞方法，只有客服端访问了，才会执行下一步，否则不会继续执行

        byte[] bytes = new byte[1024];
        int read = inputStream.read(bytes, 0, bytes.length);
        String gbk = new String(bytes, 0, read, "GBK");
        // 通过socket的输入流获取客户端的消息
        System.out.println("客户端传来的消息 "+gbk);

        OutputStream outputStream = accept.getOutputStream();

        String message = gbk + "\n" + changes(gbk);
        outputStream.write((message.getBytes("GBK")));
        // 通过socket的输出流给客户端发送消息
        System.out.println("返回给客户端的消息 \n"+message);

        accept.close();
        // 关闭流
    }

    /**
     * @Description: TODO  大写转换为小写 小写转换为大写
     * @name: changes
     * @param: [into]
     * @return: java.lang.String
     * @date: 7/2/20 11:08
     * @author: yang
     */
    public static String changes(String into) {
        StringBuilder finalString = new StringBuilder();
        for (int i = 0; i < into.length(); i++) {
            char c = into.charAt(i);
            if (Character.isUpperCase(c)) {
                // 是 大写，转换为小写
                finalString.append(Character.toLowerCase(c));
                // c 不是 i
            } else if (Character.isLowerCase(c)) {
                // 是小写，转换为 大写
                finalString.append(Character.toUpperCase(c));
            } else if (Character.isDigit(c)) {
                // 非数字添加
                finalString.append(c);
            }

        }
        return finalString.toString();
    }
}